import { useEffect, useRef } from "react";
import { TriCir } from "./TriCir";
import { CanvasTriCir } from "./CanvasTriCir";


export function useTri() {
  const ref_canvas = useRef<HTMLCanvasElement | null>(null);
  useEffect(() => {
    const canvas = ref_canvas.current;
    const ctx = canvas?.getContext('2d');
    if (!canvas || !ctx) return;
    const { width, height } = canvas.getBoundingClientRect();
    const tri = new CanvasTriCir(width, height);
    let qid: number = 0;
    const render = () => {
      canvas.width = width;
      canvas.height = height;
      tri.render(ctx);
      qid = requestAnimationFrame(render);
    };
    render();
    const pointerdown = (e: PointerEvent) => {
      const rect = canvas.getBoundingClientRect();
      tri.pointerdown(e.x - rect.x, e.y - rect.y);
    };
    const pointermove = (e: PointerEvent) => {
      const rect = canvas.getBoundingClientRect();
      tri.pointermove(e.x - rect.x, e.y - rect.y);
    };
    const pointerup = (e: PointerEvent) => {
      const rect = canvas.getBoundingClientRect();
      tri.pointerup(e.x - rect.x, e.y - rect.y);
    };
    canvas.addEventListener('pointerdown', pointerdown);
    document.addEventListener('pointermove', pointermove);
    document.addEventListener('pointerup', pointerup);
    return () => {
      canvas.removeEventListener('pointerdown', pointerdown);
      document.removeEventListener('pointermove', pointermove);
      document.removeEventListener('pointerup', pointerup);
      cancelAnimationFrame(qid);
    };
  }, []);
  return [ref_canvas];
}
